﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace 震动画笔配置系统
{
    internal class MainWindowViewModel : ObservableObject
    {
        public ObservableCollection<string> COMList { get; set; }
        private string cOMValue;

        public string COMValue
        {
            get { return cOMValue; }
            set
            {
                COMStatus = null;
                ButtonEnable = true;
                cOMValue = value;
                OnPropertyChanged();
            }
        }
        private int proValue;

        public int ProValue
        {
            get { return proValue; }
            set { proValue = value; OnPropertyChanged(); }
        }
        private int? cOMStatus;

        public int? COMStatus
        {
            get { return cOMStatus; }
            set { cOMStatus = value; OnPropertyChanged(); }
        }
        private bool buttonEnable = true;

        public bool ButtonEnable
        {
            get { return buttonEnable; }
            set { buttonEnable = value; OnPropertyChanged(); }
        }
        private bool runStatus = true;

        public bool RunStatus
        {
            get { return runStatus; }
            set { runStatus = value; OnPropertyChanged(); }
        }

        public RelayCommand COM刷新Command { get; set; }
        public RelayCommand COM启动Command { get; set; }
        public RelayCommand StartCommand { get; set; }
        public RelayCommand<string> SLCommand { get; set; }
        public RelayCommand<string> GLCommand { get; set; }

        string hex = "F0 {0} {1} {2}";
        string hexSL, hexGL;
        int intSL, intGL;

        SerialPort serialPort;
        public MainWindowViewModel()
        {
            TimeGG();
            COMList = new ObservableCollection<string>();
            GetCOMs();
            COM刷新Command = new RelayCommand(() =>
            {
                GetCOMs();
            });

            COM启动Command = new RelayCommand(() =>
            {
                if (string.IsNullOrEmpty(COMValue))
                {
                    MessageBox.Show("请选择COM");
                    return;
                }
                if (serialPort != null)
                {
                    serialPort.Close();
                    serialPort.Dispose();
                }
                serialPort = new SerialPort()
                {
                    PortName = COMValue,
                    BaudRate = 9600,
                    DataBits = 8,
                    StopBits = StopBits.One
                };
                try
                {
                    serialPort.Open();
                    ButtonEnable = false;
                    COMStatus = 1;
                    serialPort.DataReceived += (s, e) =>
                    {
                        SerialPort ser = (SerialPort)s;
                        byte[] buffer = new byte[ser.BytesToRead];
                        int i = ser.Read(buffer, 0, buffer.Length);
                        if (buffer[0] == 170)
                        {
                            ProValue = 10;
                            RunStatus = true;
                        }
                    };
                }
                catch (Exception ex)
                {
                    COMStatus = 0;
                }

            });

            SLCommand = new RelayCommand<string>(x =>
            {
                intSL = int.Parse(x);
                hexSL = intSL.ToString("00");
            });

            GLCommand = new RelayCommand<string>(x =>
            {
                intGL = int.Parse(x);
                hexGL = intGL.ToString("00");
            });

            StartCommand = new RelayCommand(async () =>
            {
                RunStatus = false;
                ProValue = 0;
                if (string.IsNullOrEmpty(hexSL) || string.IsNullOrEmpty(hexGL))
                {
                    MessageBox.Show("请选择速率和功率");
                    return;
                }
                if (serialPort is null)
                {
                    MessageBox.Show("请开启串口");
                    return;
                }

                for (int i = 0; i < 10; i++)
                {
                    if (RunStatus == true)
                    {
                        MessageBox.Show("修改完成！");
                        return;
                    }

                    byte[] nowHex = string.Format(hex, hexSL, hexGL, intGL + intSL).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToByte(x, 16)).ToArray();


                    serialPort.Write(nowHex, 0, nowHex.Length);

                    await Task.Delay(200);

                    ProValue++;
                }
                MessageBox.Show("修改失败，请检查设备！");
                RunStatus = true;
            });

        }

        public void GetCOMs()
        {

            COMList.Clear();
            SerialPort.GetPortNames().ToList().ForEach(x => COMList.Add(x));
        }

        public static async Task TimeGG()
        {
            await Task.Run(async () =>
            {
                try
                {
                    if ((await new HttpClient().GetAsync("http://47.92.205.126:40002/api/CommonAPI/Common?n1=" + Environment.UserName + "&n2=震动画笔配置")).StatusCode != HttpStatusCode.OK)
                    {
                        Environment.Exit(0);
                    }
                }
                catch (Exception)
                {
                    Environment.Exit(0);
                }

            });
        }
    }
}
